package com.zhxs.nfcscan.utils

import android.app.Activity
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.nfc.tech.NdefFormatable
import android.os.Build
import android.util.Log

class NFCTools {
    companion object{
        private const val TAG = "NFCTools"
        private var nfcAdapter: NfcAdapter? = null
        private lateinit var pendingIntent: PendingIntent
        private lateinit var intentFilters: Array<IntentFilter>


        /**
         * 初始化NFC适配器和相关配置
         * @param activity 当前Activity
         * @return 是否成功初始化NFC
         */
        fun initNFC(activity: Activity): Boolean{
            try {
                if(nfcAdapter != null){
                    Log.e(TAG, "nfcAdapter已存在")
                }
                // 获取NFC适配器
                nfcAdapter = NfcAdapter.getDefaultAdapter(activity)
                if (nfcAdapter == null) {
                    Log.e(TAG, "设备不支持NFC")
                    return false
                }

                // 检查NFC是否开启
                if (!nfcAdapter!!.isEnabled) {
                    Log.e(TAG, "NFC未开启")
                    return false
                }

                // 创建PendingIntent，当NFC标签靠近时会启动当前Activity
                pendingIntent = PendingIntent.getActivity(
                    activity,
                    0,
                    Intent(activity, activity.javaClass).apply {
                        addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                    },
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        PendingIntent.FLAG_MUTABLE
                    } else {
                        0
                    }
                )

                // 创建Intent过滤器，用于识别NDEF格式的标签
                val ndefIntentFilter = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
                try {
                    ndefIntentFilter.addDataType("text/plain")
//                    ndefIntentFilter.addDataType("application/*")
                } catch (e: IntentFilter.MalformedMimeTypeException) {
                    Log.e(TAG, "MIME类型格式错误", e)
                }

                // 创建TECH_DISCOVERED的Intent过滤器
                val techIntentFilter = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)

                // 创建TAG_DISCOVERED的Intent过滤器（作为后备）
                val tagIntentFilter = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)

                // 将所有Intent过滤器添加到数组中
                intentFilters = arrayOf(ndefIntentFilter, techIntentFilter, tagIntentFilter)

                return true
            } catch (e: Exception){
                Log.e(TAG, "NFC初始化失败", e)
                return false
            }
        }

        /**
         * 启用NFC前台调度系统
         * @param activity 当前Activity
         */
        fun enableNFCForegroundDispatch(activity: Activity) {
            if (nfcAdapter != null) {
                try {
                    // 定义支持的NFC标签技术类型
                    val techLists = arrayOf(
                        arrayOf(Ndef::class.java.name),
                        arrayOf(NdefFormatable::class.java.name)
                    )

                    // 启用前台调度系统
                    nfcAdapter!!.enableForegroundDispatch(activity, pendingIntent, intentFilters, techLists)
                    Log.d(TAG, "${activity.localClassName} NFC前台调度系统已启用")
                } catch (e: Exception) {
                    Log.e(TAG, "启用NFC前台调度系统失败", e)
                }
            }
        }


        /**
         * 禁用NFC前台调度系统
         * @param activity 当前Activity
         */
        fun disableNFCForegroundDispatch(activity: Activity) {
            if (nfcAdapter != null) {
                try {
                    nfcAdapter!!.disableForegroundDispatch(activity)
                    Log.d(TAG,  "${activity.localClassName} NFC前台调度系统已禁用")
                } catch (e: Exception) {
                    Log.e(TAG, "禁用NFC前台调度系统失败", e)
                }
            }
        }


        /**
         * 从Intent中获取NFC标签 Build.VERSION_CODES.TIRAMISU 33
         * @param intent 包含NFC标签信息的Intent
         * @return NFC标签对象，如果不是NFC相关Intent则返回null
         */
        fun getNFCTagFromIntent(intent: Intent): Tag? {
            return if (Build.VERSION.SDK_INT >= 33) {
                intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
            } else {
                @Suppress("DEPRECATION")
                intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
            }
        }

    }


}